'use client'

import { useState, useEffect, useCallback } from 'react'
import { Row, Col, Spin, Empty, Alert, Pagination } from 'antd'
import ProductCard from './ProductCard'
import SearchBar from './SearchBar'
import { ProductCardSkeleton } from './LoadingSkeleton'
import { handleNetworkError, showSuccess } from '../utils/errorHandler'

export default function ProductList() {
    const [products, setProducts] = useState([])
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState(null)
    const [searchTerm, setSearchTerm] = useState('')
    const [filterType, setFilterType] = useState('all')
    const [currentPage, setCurrentPage] = useState(1)
    const [total, setTotal] = useState(0)
    const pageSize = 12

    // 获取产品列表
    const fetchProducts = useCallback(async (search = '', type = 'all', page = 1) => {

        try {
            setLoading(true)
            setError(null)

            const params = new URLSearchParams({
                page: page.toString(),
                limit: pageSize.toString()
            })

            if (search) {
                params.append('search', search)
            }

            if (type !== 'all') {
                params.append('type', type)
            }

            const response = await fetch(`/api/products?${params}`)

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`)
            }

            const data = await response.json()

            if (data.success) {
                setProducts(data.data.products || [])
                setTotal(data.data.pagination.totalCount || 0)
            } else {
                throw new Error(data.error?.message || '获取产品列表失败')
            }
        } catch (err) {
            console.error('Error fetching products:', err)
            setError(err.message || '获取产品列表时发生错误')
            setProducts([])
            setTotal(0)
            handleNetworkError(err)
        } finally {
            setLoading(false)
        }
    }, [])

    // 初始加载
    useEffect(() => {
        fetchProducts()
    }, [fetchProducts])

    // // 搜索处理
    // const handleSearch = (search) => {
    //     setSearchTerm(search)
    //     setCurrentPage(1)
    //     fetchProducts(search, filterType, 1)
    // }

    // // 筛选处理
    // const handleFilter = (type) => {
    //     setFilterType(type)
    //     setCurrentPage(1)
    //     fetchProducts(searchTerm, type, 1)
    // }
    // 增加useCallback包裹防止重复渲染就要重复创建
    // 搜索处理
    const handleSearch = useCallback((search) => {
        setSearchTerm(search)
        setCurrentPage(1)
        fetchProducts(search, filterType, 1)
    }, [fetchProducts, filterType])

    // 筛选处理
    const handleFilter = useCallback((type) => {
        setFilterType(type)
        setCurrentPage(1)
        fetchProducts(searchTerm, type, 1)
    }, [fetchProducts, searchTerm])

    // 分页处理
    const handlePageChange = (page) => {
        setCurrentPage(page)
        fetchProducts(searchTerm, filterType, page)
        // 滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' })
    }

    // 重试处理
    const handleRetry = () => {
        fetchProducts(searchTerm, filterType, currentPage)
    }

    return (
        <div className="space-y-6">
            {/* 搜索栏 */}
            <SearchBar
                onSearch={handleSearch}
                onFilter={handleFilter}
                searchTerm={searchTerm}
                filterType={filterType}
                placeholder="搜索产品名称或描述..."
            />

            {/* 错误提示 */}
            {error && (
                <Alert
                    message="加载失败"
                    description={error}
                    type="error"
                    showIcon
                    action={
                        <button
                            onClick={handleRetry}
                            className="text-red-600 hover:text-red-800 underline"
                        >
                            重试
                        </button>
                    }
                    className="mb-4"
                />
            )}

            {/* 加载状态 */}
            {loading && (
                <ProductCardSkeleton count={pageSize} />
            )}

            {/* 产品列表 */}
            {!loading && !error && (
                <>
                    {products.length > 0 ? (
                        <>
                            {/* 结果统计 */}
                            <div className="flex justify-between items-center text-sm text-gray-600 mb-4">
                                <span>
                                    共找到 {total} 个产品
                                    {searchTerm && ` (搜索: "${searchTerm}")`}
                                    {filterType !== 'all' && ` (类型: ${filterType === 'website' ? '网站' : '应用'})`}
                                </span>
                                <span>
                                    第 {currentPage} 页，共 {Math.ceil(total / pageSize)} 页
                                </span>
                            </div>

                            {/* 产品网格 */}
                            <Row gutter={[16, 16]}>
                                {products.map((product) => (
                                    <Col
                                        key={product.id}
                                        xs={24}
                                        sm={12}
                                        md={8}
                                        lg={6}
                                        xl={6}
                                    >
                                        <ProductCard product={product} />
                                    </Col>
                                ))}
                            </Row>

                            {/* 分页 */}
                            {total > pageSize && (
                                <div className="flex justify-center mt-8">
                                    <Pagination
                                        current={currentPage}
                                        total={total}
                                        pageSize={pageSize}
                                        onChange={handlePageChange}
                                        showSizeChanger={false}
                                        showQuickJumper
                                        showTotal={(total, range) =>
                                            `第 ${range[0]}-${range[1]} 项，共 ${total} 项`
                                        }
                                    />
                                </div>
                            )}
                        </>
                    ) : (
                        /* 空状态 */
                        <div className="py-12">
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={
                                    <div className="text-gray-500">
                                        {searchTerm || filterType !== 'all' ? (
                                            <div>
                                                <p>没有找到匹配的产品</p>
                                                <p className="text-sm mt-2">
                                                    尝试调整搜索条件或筛选器
                                                </p>
                                            </div>
                                        ) : (
                                            <div>
                                                <p>还没有产品</p>
                                                <p className="text-sm mt-2">
                                                    成为第一个上传产品的用户吧！
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                }
                            />
                        </div>
                    )}
                </>
            )}
        </div>
    )
}